package com.yanqu.road.dao.impl.activity.stronghold;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.rank.cross.CrossUserRank;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossStrongholdActivityUserRankDaoImpl extends TempDao {

    /**
     * key1:activityId key2:groupId key3:conditionType
     *
     * @param activityIdList
     * @return
     */
    public Map<Integer, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>> getCrossActivityNewRankListMap(List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, Map<Integer, LinkedList<CrossUserRank>>>> dataMap = new ConcurrentHashMap<>();
        if (null == activityIdList || activityIdList.size() <= 0) {
            return dataMap;
        }
        String sql = "select * from t_c_activity_stronghold_rank where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                int groupId = rs.getInt("groupId");
                CrossUserRank data = initCrossActivityUserRank(rs);
                int activityId = data.getType();
                int conditionType = data.getBigRankType();
                Map<Integer, Map<Integer, LinkedList<CrossUserRank>>> activityIdMap = dataMap.get(activityId);
                if (null == activityIdMap) {
                    activityIdMap = new ConcurrentHashMap<>();
                    dataMap.put(activityId, activityIdMap);
                }
                Map<Integer, LinkedList<CrossUserRank>> groupMap = activityIdMap.get(groupId);
                if (null == groupMap) {
                    groupMap = new ConcurrentHashMap<>();
                    activityIdMap.put(groupId, groupMap);
                }
                LinkedList<CrossUserRank> rankList = groupMap.get(conditionType);
                if (null == rankList){
                    rankList = new LinkedList<>();
                    groupMap.put(conditionType, rankList);
                }
                rankList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean updateCrossActivityNewRankList(List<CrossUserRank> rankList, int groupId, int conditionType) {
        String sql = "REPLACE INTO t_c_activity_stronghold_rank(activityId,groupId,conditionType,rank,userId,userBaseInfo,lastUpdateTime,rankValue) " +
                "VALUES(?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            int rank = 1;
            for (CrossUserRank userRank : rankList) {
                int i = 1;
                Map<Integer, DbParameter> para = new HashMap<>();
                para.put(i++, new DbParameter(Types.INTEGER, userRank.getType()));
                para.put(i++, new DbParameter(Types.INTEGER, groupId));
                para.put(i++, new DbParameter(Types.INTEGER, conditionType));
                para.put(i++, new DbParameter(Types.INTEGER, rank));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getUserId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, userRank.getUserBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.BIGINT, userRank.getLastUpdateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, userRank.getValue().toString()));
                mapList.add(para);
                rank++;
            }
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    private CrossUserRank initCrossActivityUserRank(ResultSet rs) throws SQLException {
        CrossUserRank data = new CrossUserRank();
        data.setType(rs.getInt("activityId"));
        data.setBigRankType(rs.getInt("conditionType"));
        data.setRank(rs.getInt("rank"));
        data.setUserId(rs.getLong("userId"));
        String baseUserInfoStr = rs.getString("userBaseInfo");
        if(null == baseUserInfoStr){
            baseUserInfoStr = "";
        }
        UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
        if(null != userBaseInfo){
            data.setUserBaseInfo(userBaseInfo);
        }
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        String value = rs.getString("rankValue");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        return data;
    }
}
